<?php

define ('PATH', dirname (__FILE__).'/');
define ('PATH_LIB', PATH.'/lib/');
define ('PATH_VIEW', realpath (PATH_LIB.'/views/'));
define ('PATH_CONTROLLERS', realpath (PATH_LIB.'/controllers/'));

session_start ();

require_once (PATH.'/private/config.php');
require_once (PATH_LIB.'/controller_interface.php');
require_once (PATH_LIB.'/view_class.php');
require_once (PATH_LIB.'/user_class.php');
require_once (PATH_LIB.'/db_class.php');
require_once (PATH_LIB.'/encryption_class.php');

/* 0:  Controller [index]
 * 1:  Action [view]
 * 2+: Data [array()]
 */

if (array_key_exists ('PATH_INFO', $_SERVER) && !empty ($_SERVER['PATH_INFO'])) {
	$request = explode ('/', $_SERVER['PATH_INFO']);
	// loose the first blank entry - due to the string starting '/'
	if (sizeof ($request) > 1) {
		array_shift ($request);
	}
} else {
	$request = array ('');
}

$controller = strtolower (trim (array_shift ($request)));
define ('CONTROLLER', $controller);
if ($controller == '') {
	$controller = 'index';
}

$controller_path = realpath (PATH_CONTROLLERS.'/'.$controller.'.php');
// Check the resolved controller path looks sane.  Someone may have slipped a '../../' in there somehow.
if ($controller_path != '' && substr ($controller_path, 0, strlen (PATH_CONTROLLERS)) != PATH_CONTROLLERS) {
	die ('Access absolutely denied.');
}

if ($controller_path == '' || !file_exists ($controller_path) || !is_readable ($controller_path)) {
	$controller = 'nocontroller';
	$controller_path = PATH_CONTROLLERS.'/nocontroller.php';
}

// Check the controller loads OK - note the protection against special language constructs:
//  http://www.php.net/manual/en/function.include.php
if ((include_once ($controller_path)) === false) {
	die ('Internal error - failed to load controller: '.$controller);
}
unset ($controller_path);

$controller = 'Controller_'.ucfirst ($controller);
if (!class_exists ($controller)) {
	die ('Internal error - no controller class declared: '.$controller);
}

$valid_actions = get_class_methods ($controller);
if (!in_array ('actionView', $valid_actions)) {
	die ('Internal error - no view action for controller: '.$controller);
}

// Check for an optional action (default 'view')
if (sizeof ($request) > 0) {
	$action = 'action'.ucfirst (trim (array_shift ($request)));
	if (!in_array ($action, $valid_actions)) {
		$action = 'actionView';
	}
} else {
	$action = 'actionView';
}
unset ($valid_actions);

$controller::$action($request);

// END.

